package com.lagou.rpc.provider;

import com.lagou.rpc.api.IUserService;
import com.lagou.rpc.provider.server.RpcServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ServerBootstrapApplication implements CommandLineRunner {
    String ip = "127.0.0.1";
    int port = 8899;

    @Autowired
    RpcServer rpcServer;

    @Autowired
    IUserService userService;

    public static void main(String[] args) {
        final SpringApplication springApplication = new SpringApplication(ServerBootstrapApplication.class);
        //启动时设置spring boot不启动内嵌的web容器，不然服务端不同同时运行多个，本身该服务端也没用到web功能
        springApplication.setWebApplicationType(WebApplicationType.NONE);
        springApplication.run(args);
    }

    @Override
    public void run(String... args) throws Exception {
        if (args.length > 1) {
            for (int i = 1; i < args.length; i++) {
                String arg = args[i];
                String[] paramParts = arg.split("=");
                if (paramParts.length == 2) {
                    if ("ip".equals(paramParts[0])) {
                        ip = paramParts[1];
                    } else if ("port".equals(paramParts[0])) {
                        port = Integer.parseInt(paramParts[1]);
                    }
                }
            }
        }

        String server = String.format("%s:%s", ip, port);

        new Thread(() -> {
            rpcServer.startServer(ip, port);
        }).start();

        userService.setInstanceId("[server]" + server);
    }
}
